<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>

	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>JSP Page</title>
		<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
		<!-- 引用Vue -->
		<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
		<!-- 引入组件库 -->
		<script src="https://unpkg.com/element-ui/lib/index.js"></script>
		<script type="text/javascript" src="../js/axios.js"></script>
		<script type="text/javascript" src="../js/qs.js"></script>
		<style>
			* {
				margin: 0;
				padding: 0;
			}
			
			.app {
				width: 1024px;
				height: 500px;
			}
			
			.portlet-default {
				padding: 20px;
			}
		</style>
	</head>

	<body>
		<div id="app" class="app" style="margin: auto;">
			<div class="portlet-heading portlet-default">
				<hr>
			</div>
			<el-table :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))" style="width: 100%" show-summary :summary-method="getSummaries">

				<el-table-column label="品名型号" prop="name" align="center">
				</el-table-column>

				<el-table-column label="单位" prop="unit" align="center">
				</el-table-column>
				
				<el-table-column label="数量" align="center" prop="number">
					<template slot-scope="scope">
						<div>
							<el-input v-model="scope.row.number" @change="handleInput(scope.row)">
								<el-button slot="prepend" @click="del(scope.row)">
									<i class="el-icon-minus"></i>
								</el-button>
								<el-button slot="append" @click="add(scope.row)">
									<i class="el-icon-plus"></i>
								</el-button>
							</el-input>
						</div>
					</template>
				</el-table-column>

				<el-table-column label="金额" prop="goodTotal" align="center">
				</el-table-column>

				<el-table-column align="center">
					<template slot="header" slot-scope="scope">
						<el-select v-model="name" filterable remote reserve-keyword placeholder="请输入商品名称" :remote-method="remoteMethod" :loading="loading" @change="selectGood">
							<el-option v-for="item in goods" :key="item.value" :label="item.label" :value="item.value">

							</el-option>
						</el-select>
					</template>
					<template slot-scope="scope">
						<el-popover placement="top" width="160" v-model="scope.row.remove">
							<p>亲！确定删除此商品吗？</p>
							<div style="text-align: right; margin: 0">
								<el-button size="mini" type="text" @click="scope.row.remove=false">取消</el-button>
								<el-button type="primary" size="mini" @click="removeId(scope.row)">确定</el-button>
							</div>
							<el-button slot="reference" size="mini" type="danger" icon="el-icon-delete"></el-button>

						</el-popover>

					</template>
				</el-table-column>
			</el-table>
			<div style="text-align: center;margin-top: 10px;">
			<el-button type="info" @click="submitForm('form')">提交</el-button>
			</div>
									
									
								

		</div>
		<script>
			var vms = new Vue({
				el: "#app",
				data() {
					return {
						goods: [],
						list: [],
						name: '',
						loading: '',
						num8: 1,
						search: '',
						tableData: [],
						sum:'',
						number:'',
						unit:''

					}
				},
				methods: {
					submitForm(formName) {
					var xx=JSON.stringify(this.tableData);
						//post提交数据
								axios.post("/saveRepairgoods",
									//参数转换
									Qs.stringify({
										"xx":xx,
										"sum":this.sum,
										"number":this.number
									}, {
										arrayFormat: 'brackets'
									})
								).then(function(v) {
									//window.location.href = "/getWeixiuty";
									parent.location.reload();
								}).catch(function(e) {
									alert("出错了" + e);
								});
					},
					remoteMethod(query) {
						if(query !== '') {
							this.loading = true;
							setTimeout(() => {
								this.loading = false;
								this.goods = this.list.filter(item => {
									return item.label.toLowerCase()
										.indexOf(query.toLowerCase()) > -1;
								});
								//console.log(this.list);
							}, 200);
						} else {
							this.goods = [];
						}
					},
					handleEdit(index, row) {
						console.log(index, row);
					},
					handleDelete(index, row) {
						console.log(index, row);
					},
					handleInput: function(value) {
						if(null == value.number || value.number == "") {
							value.number = 1;
						}
						value.goodTotal = (value.number * value.price).toFixed(2);
						//保留两位小数 //增加商品数量也需要重新计算商品总价 
						//this.selected(this.multipleSelection);
					},
					add: function(addGood) {
						//输入框输入值变化时会变为字符串格式返回到js
						//此处要用v-model，实现双向数据绑定 
						if(typeof addGood.number == 'string') {
							addGood.number = parseInt(addGood.number);
						};
						addGood.number += 1;
						addGood.goodTotal = (addGood.number * addGood.price).toFixed(2);
					},
					del: function(delGood) {
						if(typeof delGood.number == 'string') {
							delGood.number = parseInt(delGood.number);
						};
						if(delGood.number > 1) {
							delGood.number -= 1;
						}
						delGood.goodTotal = (delGood.number * delGood.price).toFixed(2);
					},
					removeId(value) {
						var ids = value.id
						for(var i = 0; i < this.tableData.length; i++) {
							if(ids == this.tableData[i].id) {
								this.tableData.splice(i, 1)
							}
						}
					},
					selectGood: function(good) {
						let self = this;
						let obj = {};
						obj = this.goods.find((item) => { //this.ruleForm
							return item.value === good; //筛选出匹配数据
						});
						var goodName = obj.label;
						var price = obj.price;
						var gooUnit = obj.unit;
						var ii = 0;
						//判断购物车中已经存在该商品
						for(var i = 0; i < self.tableData.length; i++) {
							if(good == self.tableData[i].id) {
								self.tableData[i].number += 1;
								self.tableData[i].goodTotal = (self.tableData[i].number * self.tableData[i].price).toFixed(2);
								ii = 1;
								break;
							}

						}

						if(ii == 0) {
							self.tableData.push({
								id: good,
								name: goodName,
								price: price,
								number: 1,
								goodTotal: price,
								unit:gooUnit
							});
						}
						//console.log(ii);
					},
					getSummaries(param) {
				        const { columns, data } = param;
				        const sums = [];
				        columns.forEach((column, index) => {
				          if (index === 0) {
				            sums[index] = '合计';
				            return;
				          }
				          
				          const values = data.map(item => Number(item[column.property]));
				          if (!values.every(value => isNaN(value))) {
				            sums[index] = values.reduce((prev, curr) => {
				              const value = Number(curr);
				              if (!isNaN(value)) {
				                return prev + curr;
				              } else {
				                return prev;
				              }
				            }, 0);
				            sums[index] += '';
				          } else {
				            sums[index] = '';
				          }
				        });
				        this.sum = sums[3];
				        this.number=sums[2];
				        return sums;
      				}
				},
				mounted() {
					var goods = ${weixiugood};
					if(JSON.stringify(${weixiugood}) != '{}') {
						this.list = goods.map(item => {
							return {
								value: item.goo_id,
								label: item.goo_name,
								price: item.goo_price,
								number: item.goo_spec,
								unit:  item.dic_name
							};
						});
					}
					console.log(goods);
					
					
				}
			});
		</script>
		</div>
	</body>

</html>